package com.hulman.oms.web;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.hulman.oms.bean.Tool;
import com.hulman.oms.bean.ToolWarehouse;
import com.hulman.oms.bean.Result;
import com.hulman.oms.service.ToolService;
import com.hulman.oms.service.ToolWarehouseService;
import com.hulman.oms.util.NumberUtil;
import com.hulman.oms.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: maxwellens
 */
@RestController
public class ToolController
{
    @Autowired
    private ToolService toolService;

    @Autowired
    private HttpServletResponse response;
    
    @Autowired
    private ToolWarehouseService toolWarehouseService;

    @GetMapping("/tools/{id}")
    public Result findToolById(@PathVariable Integer id)
    {
        Tool tool = toolService.findToolById(id);
        return new Result(tool);
    }

    @GetMapping("/tools")
    public Result findTools(Integer page, Integer limit, Integer type, String name, String brand, String model,Integer warehouseId)
    {
        Map<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("limit", limit);
        map.put("type", type);
        map.put("name", name);
        map.put("brand", brand);
        map.put("model", model);
        map.put("warehouseId", warehouseId);
        return toolService.findToolsResult(map);
    }

    @GetMapping("/tools/index")
    public Result findToolsIndex()
    {
        Map<String, List<String>> map = new HashMap();
        List<Tool> tools = toolService.findAllTools();
        for (Tool tool : tools)
        {
            String letter = StringUtil.getPinyinFirstLetters(tool.getName().substring(0, 1));
            if (!map.containsKey(letter))
            {
                map.put(letter, new ArrayList<>());
            }
            map.get(letter).add(tool.getName());
        }
        List<Object> result = new ArrayList<>();
        for (Map.Entry<String, List<String>> entry : map.entrySet())
        {
            Map<String, Object> item = new HashMap<>();
            item.put("letter", entry.getKey());
            item.put("data", entry.getValue());
            result.add(item);
        }
        return new Result(result);
    }

    @DeleteMapping("/tools/{ids}")
    public Result deleteToolById(@PathVariable String ids)
    {
        int[] idArrays = NumberUtil.parseIntArray(ids);
        for (Integer id : idArrays)
        {
            toolService.deleteToolById(id);
        }
        return Result.SUCCESS;
    }

    @PutMapping("/tools")
    public Result saveTool(Tool tool)
    {
        toolService.saveTool(tool);
        return Result.SUCCESS;
    }

    /**
     * 通过Excel批量导入工具信息
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/tools/import")
    public Result importTools(MultipartFile file) throws IOException
    {
        File tmp = new File(System.getProperty("java.io.tmpdir") + "/" + System.currentTimeMillis() + ".xlsx");
        file.transferTo(tmp);
        try
        {
            List<Tool> tools = EasyExcel.read(tmp).head(Tool.class).sheet(0).doReadSync();
            for (Tool tool : tools)
            {
                tool.setType(Tool.parseType(tool.getExcelTypeText()));
                if (tool.getQuantity() == null)
                {
                    tool.setQuantity(0);
                }
                if(tool.getWarehouseName()!=null && tool.getWarehouseName()!=""){
                    ToolWarehouse toolWarehouse = toolWarehouseService.selectByName(tool.getWarehouseName());
                    tool.setWarehouseId(toolWarehouse.getId());
                }
                toolService.saveTool(tool);
            }
            return Result.SUCCESS;
        } catch (Exception ex)
        {
            ex.printStackTrace();
            return new Result(ex.getMessage(), null);
        }
    }

    /**
     * 导出工具列表
     *
     * @throws IOException
     */
    @GetMapping("/tools/export")
    public void exportTools(String name, String brand, String model,Integer warehouseId) throws IOException
    {
        String fileName = "工具清单.xlsx";
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("brand", brand);
        map.put("model", model);
        map.put("warehouseId", warehouseId);
        List<Tool> tools = toolService.findTools(new HashMap<>());
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet sheet0 = EasyExcel.writerSheet(0, "工具").head(Tool.class).build();
        excelWriter.write(tools, sheet0);
        excelWriter.finish();
    }

}
